package org.lzy.shop.viewmodel

import android.content.Context
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.datas.OrderCommentRequest
import org.lzy.shop.datas.OrderRequest
import org.lzy.shop.response.AddressResponse
import org.lzy.shop.response.LogisticsResponse
import org.lzy.shop.response.OrderInfoResponse
import org.lzy.shop.response.OrderRefundReason
import org.lzy.shop.response.OrderResponse
import org.lzy.shop.response.OssUpload
import org.lzy.shop.viewmodel.repository.OrderRepository
import org.lzy.shop.viewmodel.repository.lmpl.OrderRepositoryImpl

/**
 * 订单的VM层
 */
class OrderModel() : BaseViewModel(){

    private val orderRepository: OrderRepository = OrderRepositoryImpl()

    val orderListData = MutableLiveData<OrderResponse?>()
    val orderInfoData = MutableLiveData<OrderInfoResponse?>()
    val orderOpertionData = MutableLiveData<String?>()
    val orderConfirmData = MutableLiveData<String?>()
    val orderRefundData = MutableLiveData<Any?>()
    val logisticsrListData = MutableLiveData<LogisticsResponse?>()
    val getDefaultAddData = MutableLiveData<AddressResponse?>()
    val getDataReasonAddData = MutableLiveData<MutableList<OrderRefundReason>?>()
    val ossUploadLiveData = MutableLiveData<OssUpload?>()
    val uploadImgLiveData = MutableLiveData<String?>()
    val uploadImagesLiveData = MutableLiveData<List<String>?>()
    val orderCommentData = MutableLiveData<Any?>()


    /**
     * 获取订单列表
     * @param orderPresent  获取订单请求体
     */
    fun getOrder(orderPresent: OrderRequest): LiveData<OrderResponse?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getOrderList(orderPresent)
                if (response != null) {
                    orderListData.value = response
                } else {
                    errorMessage.value = "获取订单列表失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取订单列表异常"
            }
        }

        return orderListData
    }

    /**
     * 取消订单
     * @param orderId  订单id
     * @param remark  取消订单原因
     */
    fun cancelOrder(orderId: Int, remark: String?): LiveData<String?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.cancelOrder(orderId, remark)
                if (response != null) {
                    orderOpertionData.value = response
                } else {
                    errorMessage.value = "取消订单失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "取消订单异常"
            }
        }

        return orderOpertionData
    }

    /**
     * 获取订单详情
     * @param orderId  订单id
     */
    fun getOrderInfo(orderId: Int): LiveData<OrderInfoResponse?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getOrderInfo(orderId)
                if (response != null) {
                    orderInfoData.value = response
                } else {
                    errorMessage.value = "获取订单详情失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取订单详情异常"
            }
        }

        return orderInfoData
    }

    /**
     * 确认收货
     * @param orderId  订单id
     */
    fun confirmOrder(orderId: Int): LiveData<String?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.confirmOrder(orderId)
                if (response != null) {
                    orderConfirmData.value = response
                } else {
                    errorMessage.value = "确认收货失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "确认收货异常"
            }
        }

        return orderConfirmData
    }

    /**
     * 退款
     * @param orderId  订单id
     * @param reason  输入退款订单原因
     */
    fun refundOrder(orderId: Int, reason: String?): LiveData<Any?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.refundOrder(orderId, reason)
                if (response != null) {
                    orderRefundData.value = response
                } else {
                    errorMessage.value = "申请退款失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "申请退款异常"
            }
        }

        return orderRefundData
    }

    /**
     * 查看物流信息
     * @param orderId  订单id
     */
    fun getLogistics(orderId: Int): LiveData<LogisticsResponse?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getLogistics(orderId)
                if (response != null) {
                    logisticsrListData.value = response
                } else {
                    errorMessage.value = "获取物流信息失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取物流信息异常"
            }
        }

        return logisticsrListData
    }

    /**
     * 获取默认地址
     */
    fun getDefaultAddress(): LiveData<AddressResponse?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getDefaultAddress()
                if (response != null) {
                    getDefaultAddData.value = response
                } else {
                    errorMessage.value = "获取默认地址失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取默认地址异常"
            }
        }

        return getDefaultAddData
    }

    /**
     * 获得退货理由
     */
    fun getReasonData(): LiveData<MutableList<OrderRefundReason>?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getReasonData()
                if (response != null) {
                    getDataReasonAddData.value = response
                } else {
                    errorMessage.value = "获取退货理由失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取退货理由异常"
            }
        }

        return getDataReasonAddData
    }

    /**
     * 获取文件上传凭证
     */
    fun getTencentCredentials(): LiveData<OssUpload?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.getTencentCredentials()
                if (response != null) {
                    ossUploadLiveData.value = response
                } else {
                    errorMessage.value = "获取上传凭证失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取上传凭证异常"
            }
        }

        return ossUploadLiveData
    }

    /**
     * 上传单张图片
     */
    fun uploadImage(
        context: Context,
        imageUri: Uri,
        uploadUrl: String,
        tmpSecretId: String,
        tmpSecretKey: String,
        sessionToken: String
    ): LiveData<String?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.uploadImage(context, imageUri, uploadUrl, tmpSecretId, tmpSecretKey, sessionToken)
                if (response != null) {
                    Log.d("uploadUrl", "文件上传成功，URL: $response")
                    uploadImgLiveData.value = response
                } else {
                    errorMessage.value = "图片上传失败"
                    Log.d("uploadUrl", "文件上传失败")
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "图片上传异常"
                Log.d("uploadUrl", "文件上传异常: ${e.message}")
            }
        }

        return uploadImgLiveData
    }

    /**
     * 上传多张图片
     */
    fun uploadImages(
        context: Context,
        imageUris: List<Uri>,
        uploadUrl: String,
        tmpSecretId: String,
        tmpSecretKey: String,
        sessionToken: String
    ): LiveData<List<String>?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.uploadImages(context, imageUris, uploadUrl, tmpSecretId, tmpSecretKey, sessionToken)
                if (response != null) {
                    uploadImagesLiveData.value = response
                } else {
                    errorMessage.value = "多张图片上传失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "多张图片上传异常"
            }
        }

        return uploadImagesLiveData
    }

    /**
     * 提交订单评论
     */
    fun orderComment(request: OrderCommentRequest): LiveData<Any?> {
        viewModelScope.launch {
            try {
                val response = orderRepository.orderComment(request)
                if (response != null) {
                    orderCommentData.value = response
                } else {
                    errorMessage.value = "提交评论失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "提交评论异常"
            }
        }

        return orderCommentData
    }
}